package com.hospital.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件上传配置
 * 应用启动时自动创建上传目录
 *
 * @author Hospital Management System
 */
@Slf4j
@Component
public class FileUploadConfig implements CommandLineRunner {

    @Value("${file.upload.path}")
    private String uploadPath;

    // 需要创建的子目录
    private static final String[] SUB_DIRECTORIES = {
            "avatars",      // 头像
            "documents",    // 文档
            "images",       // 图片
            "reports",      // 报告
            "prescriptions",// 处方
            "others"        // 其他
    };

    @Override
    public void run(String... args) throws Exception {
        initUploadDirectories();
    }

    /**
     * 初始化上传目录
     */
    private void initUploadDirectories() {
        try {
            // 创建主上传目录
            Path mainUploadPath = Paths.get(uploadPath);
            if (!Files.exists(mainUploadPath)) {
                Files.createDirectories(mainUploadPath);
                log.info("创建主上传目录: {}", mainUploadPath.toAbsolutePath());
            }

            // 创建子目录
            for (String subDir : SUB_DIRECTORIES) {
                Path subDirPath = mainUploadPath.resolve(subDir);
                if (!Files.exists(subDirPath)) {
                    Files.createDirectories(subDirPath);
                    log.info("创建上传子目录: {}", subDirPath.toAbsolutePath());
                }
            }

            log.info("文件上传目录初始化完成，根目录: {}", mainUploadPath.toAbsolutePath());
            
            // 输出目录权限信息
            File uploadDir = mainUploadPath.toFile();
            log.info("上传目录信息 - 可读: {}, 可写: {}, 可执行: {}", 
                    uploadDir.canRead(), uploadDir.canWrite(), uploadDir.canExecute());

        } catch (Exception e) {
            log.error("初始化上传目录失败", e);
            throw new RuntimeException("初始化上传目录失败", e);
        }
    }
} 